package model

import (
	"encoding/base64"
	"ginblog/utils/errmsg"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/scrypt"
	"log"
)

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(50);not null" json:"username"`
	Password string `gorm:"type:varchar(50);not null" json:"password"`
	Role     int    `gorm:"type:int" json:"role"`
}

//验证用户是否存在
func CheckUser(username string) int {
	var user User
	db.Select("id").Where("username = ?", username).First(&user)
	if user.ID > 0 {
		return errmsg.ErrorUsernameUsed
	}
	return errmsg.SUCCESS
}

//新增用户
func AddUser(user *User) int {
	//1:方法内加密密码
	//user.Password = ScryptPw(user.Password)

	//3自定义函数加密密码
	//user.Before()
	err = db.Create(&user).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//2：定义钩子加密密码 -- 建议使用
func (user *User) BeforeSave() {
	user.Password = ScryptPw(user.Password)
}

//3自定义函数加密密码
func (user *User) Before() {
	user.Password = ScryptPw(user.Password)
}

//查询用户
func GetUser(username string) (*User, int) {
	var user User
	err = db.Where("username = ?", username).First(&user).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR
	}
	return &user, errmsg.SUCCESS
}

//查询用户列表
func GetUsers(page int, pageSize int) ([]User, int) {
	var users []User
	var total int

	err = db.Limit(pageSize).Offset((page - 1) * pageSize).Find(&users).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, 0
	}
	return users, total
}

//编辑用户
func EditUser(id int, data *User) int {
	var user User
	var maps = make(map[string]interface{})
	maps["username"] = data.Username
	maps["role"] = data.Role
	err = db.Model(&user).Where("id = ?", id).Update(maps).Error

	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//删除用户
func DeleteUser(id int) int {
	var user User
	err = db.Where("id = ?", id).Delete(&user).Error //软删除
	//err = db.Where("id = ?", id).Unscoped().Delete(&user).Error //删除
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//密码加密
func ScryptPw(passsword string) string {
	const KenLen = 10
	salt := make([]byte, 8)
	salt = []byte{12, 32, 4, 5, 55, 22, 222, 11}

	HashPw, err := scrypt.Key([]byte(passsword), salt, 16384, 8, 1, KenLen)
	if err != nil {
		log.Fatal(err)
	}
	Fpw := base64.StdEncoding.EncodeToString(HashPw)
	return Fpw
}

//登录验证
func CheckLogin(username string, password string) int {
	var user User
	db.Where("username = ?", username).First(&user)

	if user.ID == 0 {
		return errmsg.ErrorUserNotExist
	}

	if user.Password != ScryptPw(password) {
		return errmsg.ErrorPasswordWrong
	}

	if user.Role != 0 {
		//return errmsg.ERROR
	}

	return errmsg.SUCCESS
}
